<!-- 导入导出记录 -->
<template>
  <a-spin tip="正在执行,请等待..." size="large" :spinning="loading" style="font-size: 18px">
  <div class="lanjian-content pdd">
    <div class="tableOperator">
      <div class="btn-box" >
        <a-upload
          :multiple="true"
          :file-list="fileList"
          :customRequest="customUpload"
          :before-upload="beforeFileUpload"
          :showUploadList="false"
          class="mr8"
        >
          <a-button>
            <a-icon type="upload"/>
            导入
          </a-button>
          <a-tooltip>
            <template slot="title">
              仅支持上传zip格式的文件。
            </template>
            <a-icon type="question-circle" style="margin-left: 8px;color: orange;" />
          </a-tooltip>
        </a-upload>
<!--        <a-button type="primary" @click="exportAll">
          导出提报
        </a-button>-->
      </div>
      <div class="input-box">
        <a-range-picker v-model="queryParam.attr" @change="onChange" class="m-r-8" />
        <a-select placeholder="请选择类型" v-model="queryParam.type" :allowClear="true" class="m-r-8">
          <a-select-option
            value="导入"
            title="导入">
            导入
          </a-select-option>
          <a-select-option
            value="导出"
            title="导出">
            导出
          </a-select-option>
        </a-select>
        <a-button type='primary' class='m-r-8 ClassA' @click='search' title='搜索'>
          <span class='icon iconfont'>&#xe666;</span>
        </a-button>
        <a-button class='resBtn ClassA' @click='loadtable' title='重置'>
          <span class='icon iconfont'>&#xe672;</span>
        </a-button>
      </div>
    </div>
    <a-table
      class="table-box"
      :columns="columns"
      bordered
      :data-source="dataSource"
      :pagination="pagination"
      @change="tablePaginationChange"
      :rowKey="(record,index)=>{return index}"
      >
    <span
        slot="action"
        slot-scope="record"
        class="actionIcons">
        <span @click="download(record)" title='下载'>
          <i class='icon iconfont' >&#xe674;</i>
        </span>

      </span>
    </a-table>
  </div>
  </a-spin>
</template>

<script>
import {
  getImportAndExportRecords, uploadFile, exportAlls, streamToBuffer
} from '@/utils/JsonTools'
import moment from 'moment'
import { saveAs } from 'file-saver'
import fs from 'fs'
 import {unzipFile} from "@/utils/fileUtils";
import eventBus from "@/utils/event";
export default {
  name: 'ImportAndExportRecords',
  data () {
    return {
      loading:false,
      loading2:false,
      // 列
      columns: [
        {
          title: '序号',
          width: 70,
          align: 'center',
          customRender: (text, record, index) => `${index + 1}`
        },
        {
          title: '类型',
          dataIndex: 'type',
          key: 'type',
          align: 'center',
          ellipsis: true,
          width: 160,
        },
        {
          title: '导入导出内容',
          dataIndex: 'module',
          key: 'module',
          align: 'center',
          ellipsis: true,
          width: 220,
        },
        {
          title: '文件',
          dataIndex: 'file',
          key: 'file',
          align: 'center'
        },
/*        {
          title: '模块',
          dataIndex: 'module',
          key: 'module',
          align: 'center',
          ellipsis: true
        },*/
        {
          title: '操作时间',
          dataIndex: 'date',
          key: 'date',
          align: 'center',
          ellipsis: true,
          width: 240,
        },
        {
          title: '操作',
          key: 'operation',
          align: 'center',
          width: 120,
          scopedSlots: { customRender: 'action' }
        }
      ],
      dataSource: [],
      queryParam: {
        type: undefined,
        attr: []
      },
      // 分页参数
      pagination: {
        current: 1,
        // defaultCurrent: 1,
        total: 0, // 总数
        showSizeChanger: true,
        // 是否可以快速跳转至某页
        showQuickJumper: true,
        pageSizeOptions: ['10', '20', '40', '80', '100'],
        // showTotal: total => '共 ${total} 条', // 分页中显示总的数据
        // hideOnSinglePage: true, // 只有一页时是否隐藏分页器
        pageSize: 10 // 每页条数，所有页设置统一的条数
      },
      fileList: []
    }
  },
  mounted () {
    this.loadtable()
  },
  methods: {
    moment,
    // 搜索时间选择器
    onChange (date, dateString) {
      this.queryParam.attr = [...dateString]
    },
    tablePaginationChange (pagination) {
      // 重新设置当前页
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
    },
    // 查询反馈意见
    loadtable () {
      this.queryParam.type = undefined
      this.queryParam.attr = []
      getImportAndExportRecords().then(res => {
        this.dataSource = [...res].reverse()
      })
    },
    formatDate(value, format) {
      const formatNumber = n => `0${n}`.slice(-2)
      const date = value
      const formatList = ['Y', 'M', 'D', 'h', 'm', 's']
      const resultList = []
      resultList.push(date.getFullYear().toString())
      resultList.push(formatNumber(date.getMonth() + 1))
      resultList.push(formatNumber(date.getDate()))
      resultList.push(formatNumber(date.getHours()))
      resultList.push(formatNumber(date.getMinutes()))
      resultList.push(formatNumber(date.getSeconds()))
      for (let i = 0; i < resultList.length; i++) {
        format = format.replace(formatList[i], resultList[i])
      }
      return format
    },
    // 搜索反馈意见
    search () {
      console.log(this.queryParam)
      getImportAndExportRecords().then(res => {
        let dates, datee
        let arr = []
        let a, b
        if (this.queryParam.type === undefined) {
          a = ''
        } else {
          a = this.queryParam.type
        }
        console.log(this.queryParam.attr)
        // eslint-disable-next-line eqeqeq
        if (this.queryParam.attr.length > 0 && this.queryParam.attr[0] != '') {
          dates = this.formatDate(new Date(Date.parse(this.queryParam.attr[0])), 'Y-M-D')
          datee = this.formatDate(new Date(Date.parse(this.queryParam.attr[1])), 'Y-M-D')
        }
        res.forEach(element => {
          let datel = this.formatDate(new Date(Date.parse(element.date)), 'Y-M-D')
          if (this.queryParam.attr.length > 0) {
            // eslint-disable-next-line no-undef
            if (dates <= datel && datel <= datee) {
              if (a === '') {
                arr.push(element)
              } else {
                if (element.type.indexOf(a) > -1) {
                arr.push(element)
                }
              }
            }
          } else {
            if (a === '') {
              arr.push(element)
            } else {
              if (element.type.indexOf(a) > -1) {
                arr.push(element)
              }
            }
          }
        })
        this.dataSource = [...arr]
      })
    },
    // 上传验证
    beforeFileUpload (file) {
      if (file.name.substring(0, file.name.indexOf('.')).length > 200) {
        this.$message.error('上传文件名字不得超过200字')
        return false
      }
      let isLt2M = file.size / 1024 / 1024
      if (isLt2M > 200) {
        this.$message.error('只允许上传200M以下的文件')
        return false
      }
      let fileExt = file.name.slice(file.name.lastIndexOf('.') + 1)
      let fileTypeArr = ['zip']
      if (fileTypeArr.indexOf(fileExt) === -1) {
        this.$message.error('非法的文件类型')
        return false
      }
      return true
    },
    customUpload (file) {
      this.loading=true
      // 文件导入并解析
      unzipFile(file.file).then(res => {
        // eslint-disable-next-line eqeqeq
        this.loading=false
        if (res == 0) {
          this.$message.error('导入失败')
          return
        }
        eventBus.emit('updatewhel')
        this.$message.success('导入成功')
        setTimeout(s => {
          this.loadtable()
        }, 1000)
      })
    },
    // 构造formData
    handleUpload (file) {
      const formData = new FormData()
      let timestamp = new Date().getTime()
      formData.append('files', file)
      formData.append('fileUid', file.uid)
      formData.append('totalBytes', file.size)
      formData.append('time', timestamp)
      this.imagerAdd(formData)
    },
    // 上传
    async imagerAdd(formData) {

    },
    exportAll() {
      this.loading=true
      // 导出提报
      // eslint-disable-next-line no-undef
      exportAlls().then(res => {
        // eslint-disable-next-line eqeqeq
        if (res.status == 0) {
          //this.loading=false
          this.$message.error('导出失败')
          return
        } else {
          console.log(res)
          let fileb = fs.createReadStream(res.path)
          let fsname = res.fname
          console.log('fsname-----' + fsname)
          streamToBuffer(fileb).then(res => {
            let data = res
            let contents = new Uint8Array(data.length)
            for (let i = 0; i < data.length; i++) {
              contents[i] = data[i]
            }
            //this.loading=false
            // eslint-disable-next-line no-undef
            let expname = fsname.replace(/[\d]+/, this.getcurDate())
            saveAs.saveAs(new Blob([contents], { type: 'application/zip' }), expname)
          })
          this.loadtable()
          this.$message.success('导出成功')
        }
      })
    },
    download (record) {
      this.loading=true
      let fileb = fs.createReadStream(record.path)
      let fsname = record.fname
      console.log('fsname-----' + fsname)
      streamToBuffer(fileb).then(res => {
        let data = res
        let contents = new Uint8Array(data.length)
        for (let i = 0; i < data.length; i++) {
          contents[i] = data[i]
        }
        this.loading=false
        // eslint-disable-next-line no-undef
        //let expname = fsname.replace(/[\d]+/, this.getcurDate())
        saveAs.saveAs(new Blob([contents], { type: 'application/zip' }), fsname)
      })
    },
    getcurDate() {
      let currentDate = new Date()
      let year = currentDate.getFullYear().toString()
      let month = (currentDate.getMonth() + 1).toString()
      if (month.length === 1) {
        month = '0' + month
      }
      let date = currentDate.getDate().toString()
      if (date.length === 1) {
        date = '0' + date
      }
      let hour = currentDate.getHours().toString()
      if (hour.length === 1) {
        hour = '0' + hour
      }
      let minute = currentDate.getMinutes().toString()
      if (minute.length === 1) {
        minute = '0' + minute
      }
      let second = currentDate.getSeconds().toString()
      if (second.length === 1) {
        second = '0' + second
      }
      return year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second
    }
  }
}
</script>
<style lang="scss">
// 滚动条背景颜色
.ant-form::-webkit-scrollbar,
.info::-webkit-scrollbar {
  height: 9px;
  width: 9px;
  background-color: #fcfcfc;
}
.table-box {
  height: calc(100% - 65px);
}
// 滚动条颜色
.ant-form::-webkit-scrollbar-thumb,
.info::-webkit-scrollbar-thumb {
  border-radius: 9px;
  background-color: #000000;
}

.ant-form-item label{
  font-weight: bold;
}
.ant-table-body{
  height: 65vh;
}

</style>
